package com.ys.web.api.assistant.service.impl;

import cn.hutool.core.util.IdUtil;
import com.ys.base.BaseConstants;
import com.ys.utils.base.http.McodeHandler;
import com.ys.utils.base.j2se.DateHandler;
import com.ys.utils.base.j2se.Logger;
import com.ys.utils.base.j2se.StringHandler;
import com.ys.utils.help.UserUtils;
import com.ys.utils.redis.Redis;
import com.ys.utils.redis.key.GroupKey;
import com.ys.utils.spring.config.SystemError;
import com.ys.web.api.assistant.service.GroupAssistantService;
import com.ys.web.api.assistant.vo.GroupAssistantVO;
import com.ys.web.ws.bean.MessageRequestBean;
import com.ys.web.ws.send.service.MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @ 名称:
 * @ 创建人: dhf
 * @ 参数： null
 * @ 创建时间: 2022/5/10
 * @ 修改人和其它信息
 * @ 返回值:
 */
@Slf4j
@Service
public class GroupAssistantServiceImpl implements GroupAssistantService {


    @Autowired
    private MessageService messageService;

    @Override
    public void thirdparty(GroupAssistantVO groupAssistantVO) {
        Long groupId = null;
        try {
            groupId = McodeHandler.from32Radix(groupAssistantVO.getGroupCode());
        } catch (Exception e) {
            Logger.error("群助手，群id转换异常：" + groupAssistantVO.getGroupCode(), e);
            SystemError.wrapBs("500", "群助手，标识符换异常");
        }

        if (StringHandler.isNotEmpty(groupId)) {
            String groupAssistantTokenKey = GroupKey.groupAssistantToken(groupId);
            String token = Redis.str.get(groupAssistantTokenKey);
            if (groupAssistantVO.getToken().equals(token)) {
                MessageRequestBean message = new MessageRequestBean();

                message.setData(groupAssistantVO.getData());
                message.setGroupId(String.valueOf(groupId));
                message.setCreateTime(DateHandler.getDate(new Date(), BaseConstants.BASE_FORMAT));
                message.setMessageId(IdUtil.simpleUUID());
                message.setWidth(groupAssistantVO.getWidth());
                message.setHeight(groupAssistantVO.getHeight());
                message.setCode(groupAssistantVO.getCode());
                message.setFrom(UserUtils.ASSISTANT.getUserId());
                message.setAvatarUrl(UserUtils.ASSISTANT.getAvatarUrl());
                message .setUserName(UserUtils.ASSISTANT.getNickName());

                messageService.sendMessageGroup(message);

            } else {
                SystemError.wrapBs("202", "令牌有误，请确认令牌有效性");
            }
        } else {
            SystemError.wrapBs("202", "群标识有误");
        }
    }
}
